package com.kaochong.xcx.service.impl;

import com.google.common.collect.Lists;

import com.kaochong.common.util.BeanConvertUtil;
import com.kaochong.xcx.cache.BookCategoryCache;
import com.kaochong.xcx.cache.WordBookCache;
import com.kaochong.xcx.enums.ResultEnum;
import com.kaochong.xcx.enums.WordBookIsNewStatus;
import com.kaochong.xcx.enums.WordBookStatus;
import com.kaochong.xcx.exception.KaoChongException;
import com.kaochong.xcx.entity.BookCategory;
import com.kaochong.xcx.entity.UserInfo;
import com.kaochong.xcx.entity.WordBook;
import com.kaochong.xcx.pojo.dto.TargetPeopleDTO;
import com.kaochong.xcx.pojo.vo.BookCategoryVO;
import com.kaochong.xcx.pojo.vo.WordBookVO;
import com.kaochong.xcx.dao.BookCategoryMapper;
import com.kaochong.xcx.dao.WordBookMapper;
import com.kaochong.xcx.service.UserInfoService;
import com.kaochong.xcx.service.UserService;
import com.kaochong.xcx.service.WordBookService;
import com.kaochong.xcx.utils.CalculateUtil;
import com.kaochong.xcx.web.aspect.CurrentUser;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author han
 * @date 2018-06-21 15:57
 */
@Service
@Slf4j
public class WordBookServiceImpl implements WordBookService {
	
	@Autowired
	WordBookMapper wordBookMapper;
	
	@Autowired
	WordBookCache wordBookCache;
	
	@Autowired
	BookCategoryMapper bookCategoryMapper;
	
	@Autowired
	BookCategoryCache bookCategoryCache;
	
	@Autowired
	UserService userService;
	
	@Autowired
	UserInfoService userInfoService;
	
	@Override
	public List<WordBookVO> getAllOnShowList() {
		List<WordBook> list = wordBookCache.getAll();
		if (list.isEmpty()) {
			list = wordBookMapper.findOnshowList();
			wordBookCache.save(list);
		}
		return BeanConvertUtil.convert(list, WordBookVO.class);
	}
	
	@Override
	public List<WordBookVO> getPutawayList() {
		List<WordBookVO> list = getAllOnShowList();
		List<WordBookVO> result = Lists.newArrayList();
		for (WordBookVO wordBookVO : list) {
			if (WordBookStatus.OPEN.getCode().equals(wordBookVO.getStatus())) {
				result.add(wordBookVO);
			}
		}
		return BeanConvertUtil.convert(result, WordBookVO.class);
	}
	
	@Override
	public WordBookVO getWordBookVO(Integer target) {
		WordBook wordBook = wordBookCache.getByTarget(target);
		if (null == wordBook) {
			log.error("【背单词-单词书】单词书选择有误：target={}", target);
			throw new KaoChongException(ResultEnum.TARGET_CHOOSE_ERROR);
		}
		return BeanConvertUtil.convert(wordBook, WordBookVO.class);
	}
	
	@Override
	public WordBook getWordBook(Integer target) {
		WordBook wordBook = wordBookCache.getByTarget(target);
		if (null == wordBook) {
			log.error("【背单词-单词书】单词书选择有误：target={}", target);
			throw new KaoChongException(ResultEnum.TARGET_CHOOSE_ERROR);
		}
		if (2 != wordBook.getStatus()) {
			log.error("【背单词-单词书】单词书选择有误：target={}", target);
			throw new KaoChongException(ResultEnum.TARGET_CHOOSE_ERROR);
		}
		return wordBook;
	}
	
	@Override
	public Integer getNewBookCount() {
		List<WordBookVO> list = getAllOnShowList();
		Integer count = 0;
		for (WordBookVO vo : list) {
			if (WordBookStatus.OPEN.getCode().equals(vo.getStatus())
					&& WordBookIsNewStatus.NEW_BOOK.getCode().equals(vo.getIsnew())) {
				count++;
			}
		}
		return count;
	}
	
	@Override
	public List<WordBookVO> getNewBookList() {
		List<WordBookVO> list = getAllOnShowList();
		List<WordBookVO> newbooks = Lists.newArrayList();
		for (WordBookVO vo : list) {
			if (WordBookStatus.OPEN.getCode().equals(vo.getStatus())
					&& WordBookIsNewStatus.NEW_BOOK.getCode().equals(vo.getIsnew())) {
				newbooks.add(vo);
			}
		}
		return newbooks;
	}
	
	@Override
	public Map<String, Object> findWordBookByCategoryId(CurrentUser user, Integer categoryId) {
		Map<String, Object> resultMap = new HashMap<>();
		
		List<WordBookVO> books = Lists.newArrayList();
		
		WordBookVO userBook = new WordBookVO();
		
		// 查询已背人数
		List<TargetPeopleDTO> everyTargetCount = userService.findEveryTargetCount();
		
		List<UserInfo> list = userInfoService.findByUserId(user.getId());
		
		List<WordBookVO> onShowList = getAllOnShowList();
		
		if (user.getTarget() != null) {
			for (WordBookVO wordBookVO : onShowList) {
				if (wordBookVO.getTarget().equals(user.getTarget())) {
					for (TargetPeopleDTO dto : everyTargetCount) {
						if (user.getTarget().equals(dto.getTarget())) {
							wordBookVO.setPeopleNum(dto.getCount());
							break;
						}
					}
					for (UserInfo userInfo : list) {
						if (userInfo.getTarget().equals(user.getTarget())) {
							Integer stu = userInfo.getStudyWordsNum();
							Integer tot = wordBookVO.getWordsNum();
							
							Integer rate = CalculateUtil.divideRoundDown(stu, tot);
							wordBookVO.setSchedule(rate);
							break;
						}
					}
					String intro = wordBookVO.getIntro();
					String[] split = {};
					if (StringUtils.isNotBlank(intro)) {
						split = intro.split("<br>");
					}
					wordBookVO.setIntroArray(Arrays.asList(split));
					userBook = wordBookVO;
				}
			}
		}
		
		// 0代表热门直接查单词书
		if (0 == categoryId) {
			for (WordBookVO wordBookVO : onShowList) {
				if (1 == wordBookVO.getIsHost()) {
					Integer target = wordBookVO.getTarget();
					for (TargetPeopleDTO dto : everyTargetCount) {
						if (target.equals(dto.getTarget())) {
							wordBookVO.setPeopleNum(dto.getCount());
							continue;
						}
					}
					String intro = wordBookVO.getIntro();
					String[] split = {};
					if (StringUtils.isNotBlank(intro)) {
						split = intro.split("<br>");
					}
					wordBookVO.setIntroArray(Arrays.asList(split));
					books.add(wordBookVO);
				}
			}
		} else {
			for (WordBookVO wordBookVO : onShowList) {
				if (wordBookVO.getCategoryId().equals(categoryId)) {
					Integer target = wordBookVO.getTarget();
					for (TargetPeopleDTO dto : everyTargetCount) {
						if (target.equals(dto.getTarget())) {
							wordBookVO.setPeopleNum(dto.getCount());
							continue;
						}
					}
					String intro = wordBookVO.getIntro();
					String[] split = {};
					if (StringUtils.isNotBlank(intro)) {
						split = intro.split("<br>");
					}
					wordBookVO.setIntroArray(Arrays.asList(split));
					books.add(wordBookVO);
				}
			}
		}
		
		for (WordBookVO book : books) {
			for (UserInfo userInfo : list) {
				if (book.getTarget().equals(userInfo.getTarget())) {
					Integer stu = userInfo.getStudyWordsNum();
					Integer tot = book.getWordsNum();
					
					Integer rate = CalculateUtil.divideRoundDown(stu, tot);
					book.setSchedule(rate);
					continue;
				}
			}
		}
		
		resultMap.put("userBook", userBook);
		resultMap.put("wordbooks", books);
		return resultMap;
	}
	
	@Override
	public List<BookCategoryVO> findBookCategory() {
		List<BookCategoryVO> category = bookCategoryCache.getAllCategory();
		if (category.isEmpty()) {
			List<BookCategory> categories = bookCategoryMapper.findByStatus(1);
			category = BeanConvertUtil.convert(categories, BookCategoryVO.class);
			bookCategoryCache.lRightPushAll(category);
		}
		return category;
	}
}
